import 'package:easy_chat_app/commons/enum/AppLoginStateEnum.dart';
import 'package:easy_chat_app/commons/model/AppTokenInfo.dart';
import 'package:easy_chat_app/commons/model/Result.dart';
import 'package:easy_chat_app/commons/utils/StringUtils.dart';
import 'package:easy_chat_app/commons/ws/AppWSClient.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'HttpUtils.dart';

class TokenUtils {
  static const String tokenStoreKey = "token";

  static String _token = "";

  static final Logger logger = Logger();

  static Future<Result> login(String phone, String password) async {
    Result<String> result = await HttpUtils.login(phone, password);
    if (result.code == 0 && StringUtils.isNotEmpty(result.data)) {
      String token = result.data!;
      _token = token;
      final SharedPreferences sharedPreferences =
          await SharedPreferences.getInstance();
      sharedPreferences.setString(tokenStoreKey, token);
      // 开启WS连接
      await WSWebsocketClient.instance.initWSConnect();
    }
    logger.i("result: $result");
    return result;
  }

  static Future<Result> register(String phone, String password) async {
    Result<String> result = await HttpUtils.register(phone, password);
    if (result.code == 0 && StringUtils.isNotEmpty(result.data)) {
      String token = result.data!;
      _token = token;
      final SharedPreferences sharedPreferences =
          await SharedPreferences.getInstance();
      sharedPreferences.setString(tokenStoreKey, token);
    }
    logger.i("result: $result");
    return result;
  }

  static Future<void> logout() async {
    Result<String?> result = await HttpUtils.logout();
    logger.i("退出登录: $result");
    final SharedPreferences sharedPreferences =
        await SharedPreferences.getInstance();
    sharedPreferences.remove(tokenStoreKey);
    _token = "";
    await WSWebsocketClient.instance.closeWSConnect();
  }

  static Future<void> loadAndCheckToken() async {
    final SharedPreferences sharedPreferences =
        await SharedPreferences.getInstance();
    _token = StringUtils.defaultIfEmpty(
        sharedPreferences.getString(tokenStoreKey), "");

    // 校验Token是否有效
    if (StringUtils.isNotEmpty(_token)) {
      Result<AppTokenInfo> result = await HttpUtils.getLoginUserInfo();
      if (result.code == AppLoginStatusEnum.tokenTimeout.code) {
        _token = "";
      }
    }
  }

  static String token() {
    return _token;
  }

  static bool hasToken() {
    return StringUtils.isNotEmpty(_token);
  }

  static bool isTimeout(Result result) {
    return AppLoginStatusEnum.tokenTimeout.code == result.code;
  }
}
